<template>
  <div class="container">
    <!-- header-search组件 -->
    <div v-if="headShow">
      <header-search @reset="handlerReset" @search="handlerSearch">
        <template #search>
          <el-form-item small>
            <template slot="label">
              <div class="label">广告图描述</div>
            </template>
            <el-input
              ref="searchRef"
              v-model="pageData.advimgdesc"
              size="small"
              placeholder="请输入广告位名称"
            />
          </el-form-item>
          <el-form-item small>
            <template slot="label">
              <div class="label">广告图位置</div>
            </template>

            <el-select
              v-model="pageData.advimgpos"
              clearable
              size="small"
              style="width: 230px"
              placeholder="请选择广告位"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </template>
      </header-search>
    </div>
    <!-- buttom组件 -->
    <header-button
      :head-show.sync="headShow"
      :check-data.sync="checkData"
      @open="openDialog"
      @loading="handlerLoading"
    >
      <template v-if="delBtnShow" #del>
        <el-button
          type="danger"
          icon="el-icon-delete"
          plain
          size="medium"
          @click="delChecked"
        >删除</el-button>
      </template>
    </header-button>
    <!-- buttom结束 -->
    <!-- table区域 -->
    <el-table
      v-loading="loading"
      border
      :data="tableData"
      style="margin-top: 14px"
      :header-cell-style="{ color: '#646464' }"
      type="index"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" show-overflow-tooltip />
      <el-table-column label="#" width="60" type="index" />
      <el-table-column
        v-if="checkData[0].isckecked"
        label="广告图位"
        prop="advposname"
      />
      <el-table-column
        v-if="checkData[1].isckecked"
        label="广告图描述"
        prop="advimgdesc"
      />
      <el-table-column
        v-if="checkData[2].isckecked"
        label="广告图"
        prop="advimgsrc"
      >
        <template slot-scope="scope">
          <el-image
            style="width: 120px; height: 60px"
            :src="$ImgUrl + scope.row.advimgsrc"
            fit="fill"
          />
          <!-- <span style="margin-left: 10px">{{$ImgUrl+scope.row.advimgsrc }}</span> -->
        </template>
      </el-table-column>
      <el-table-column
        v-if="checkData[3].isckecked"
        label="广告图链接"
        prop="advimglink"
      />

      <el-table-column label="操作" align="center">
        <template #default="{ row }">
          <el-button
            type="primary"
            icon="el-icon-edit"
            circle
            @click="handlerEdit('edit', row.id)"
          />
          <el-button
            type="danger"
            icon="el-icon-delete"
            circle
            @click="handlerDel(row.id)"
          />
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :visible.sync="visible" width="45%" :before-close="handleClose">
      <!-- 表单 -->
      <div slot="title" class="header-title">
        <!-- <div>添加分类</div> -->
        <div>{{ title }}</div>
      </div>
      <el-form
        ref="formRef"
        label-width="120px"
        size="medium"
        :model="formData"
        :rules="rules"
      >
        <el-form-item prop="advimgpos">
          <template #label>
            <span class="title"> 广告位 </span>
          </template>
          <el-select v-model="formData.advimgpos" placeholder="请选择广告位">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="advimgdesc">
          <template #label>
            <span class="title"> 广告位描述 </span>
          </template>
          <el-input
            v-model="formData.advimgdesc"
            size="medium"
            placeholder="请输入广告图描述"
            style="width: 550px"
            type="textarea"
            :rows="2"
          />
        </el-form-item>
        <el-form-item prop="advimglink">
          <template #label>
            <span class="title"> 广告图链接 </span>
          </template>
          <el-input
            v-model="formData.advimglink"
            size="medium"
            placeholder="请输入广告图链接"
            style="width: 550px"
          />
        </el-form-item>
        <el-form-item prop="advimgsrc">
          <template #label>
            <span class="title"> 广告图 </span>
          </template>
          <el-upload
            ref="upload"
            action="http://124.223.14.236:8060/admin/common/upload?type=images"
            multiple
            :limit="1"
            auto-upload
            :headers="headerObj"
            :on-change="fileChange"
            :on-remove="fileRemove"
            :on-success="fileSuccess"
            :before-remove="fileBeforeRemove"
            :file-list="fileList"
            list-type="picture"
          >
            <el-button v-if="btnisShow" size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>

      <span slot="footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" autofocus @click="submit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分页组件 -->
    <lay-page
      :limit.sync="pageData.limit"
      :page.sync="pageData.page"
      :count="count"
    />
  </div>
</template>

<script>
import { getImgListApi, addImgApi, getImgInfoApi, delImgApi, getadvposAllApi, editImgApi } from '@/api/advimg'
import { getToken } from '@/utils/auth'

export default {
  name: 'TagPage',
  data() {
    return {
      btnisShow: true,
      checkedList: [],
      // 广告位列表
      advposList: [],
      // 回显的数组
      fileList: [],
      headerObj: {
        'X-Token': getToken()
      },
      delBtnShow: false,
      checked: true,
      // headTip: '关闭搜索区',
      loading: false,
      headShow: true,
      title: '',
      // searchContent: '',
      pageData: {
        page: 1,
        limit: 10,
        advimgdesc: '', // 广告图描述
        advimgpos: '' // 广告图位置
      },
      tableData: [],
      count: 0,
      visible: false, // 对话框的状态
      drawerType: '', // 类型 添加/修改
      formData: {
        advimgdesc: '',
        advimglink: '',
        advimgpos: '',
        advimgsrc: null
      },
      formType: '',
      // searchContent: '',
      rules: {
        advimgpos: [
          { required: true, message: '广告位类型必须！', trigger: 'blur' }
        ],
        advimgdesc: [
          { required: true, message: '描述类型必须！', trigger: 'blur' }
        ],
        advimglink: [
          { required: true, message: '链接类型类型必须！', trigger: 'blur' }
        ],
        advimgsrc: [
          {
            required: true,
            message: '至少选择一个活动性质',
            trigger: ['blur', 'change']
          }
        ]
      },
      checkData: [
        { id: 1, name: '广告图位', isckecked: true },
        { id: 2, name: '广告图描述', isckecked: true },
        { id: 3, name: '广告图', isckecked: true },
        { id: 4, name: '广告图链接', isckecked: true }
      ],
      options: []

    }
  },

  // 分页
  watch: {
    'pageData.limit'(val) {
      this.getImgList()
    },
    'pageData.page'(val) {
      this.getImgList()
    }
  },
  created() {
    this.getImgList()
    this.getadvposList()
  },
  methods: {
    // 获取tag列表
    async getImgList() {
      const res = await getImgListApi(this.pageData)
      console.log(res)
      this.tableData = res.data
      // this.tableData.forEach(item => {
      //   item.advimgsrc = this.$ImgUrl + item.advimgsrc
      // })
      this.count = res.count
    },
    // 获取广告位列表
    async getadvposList() {
      const res = await getadvposAllApi()
      this.options = res.map(item => {
        return { value: item.id.toString(), label: item.advposname }
      })
    },
    openDialog(type) {
      console.log(type)
      this.btnisShow = true
      this.formType = type
      this.title = '添加广告图'
      this.visible = true
    },
    // 关闭对话框 清空表单
    dialogClose() {
      this.visible = false
      this.formData = {
        advimgdesc: '',
        advimglink: '',
        advimgpos: '',
        advimgsrc: null
      }
      // 清空文件列表
      this.$refs.upload.clearFiles()
      // 清空表单校验
      this.$refs.formRef.clearValidate()
    },
    // 搜索请求
    handlerSearch() {
      console.log(this.pageData)
      this.getImgList()
    },
    // 重置
    handlerReset() {
      this.pageData.advimgdesc = ''
      this.pageData.advimgpos = ''
      this.getImgList()
    },

    handleClose(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          this.dialogClose()
        })
        .catch((_) => {})
    },
    // 设置刷新loading
    async handlerLoading() {
      this.tableData = []
      this.loading = true
      await this.getImgList()
      this.loading = false
    },
    // table checked变化
    handleSelectionChange(rows) {
      // rows是选中的row
      this.checkedList = rows
      console.log(rows)
      if (rows.length > 0) {
        this.delBtnShow = true
      } else {
        this.delBtnShow = false
      }
    },
    // 删除选中的
    delChecked() {
      this.checkedList.forEach(async item => {
        try {
          await delImgApi(item.id)
          this.$message('删除成功')
        } catch (err) {
          console.log(err)
        }
      })
      this.getImgList()
    },
    // 表单提交
    async submit() {
      await this.$refs.formRef.validate()
      console.log(this.formData)
      if (this.formType === 'add') {
        console.log(this.formData)
        await addImgApi(this.formData)
        this.$message.success('添加分类成功')
      } else {
        console.dir(this.formData)
        await editImgApi(this.formData)
        this.$message.success('修改分类成功')
      }

      this.getImgList()

      this.dialogClose()
    },
    fileChange(uploadFile, fileList) {
      // this.formData.advimgsrc = uploadFile
      // console.log(fileList.length)
      if (fileList.length !== 0) {
        this.btnisShow = false
        this.$refs.formRef.validateField('advimgsrc')
      }
    },
    fileRemove(uploadFile, fileList) {
      console.log(fileList.length)
      if (fileList.length === 0) {
        this.btnisShow = true
        this.formData.advimgsrc = null
        this.$refs.formRef.validateField('advimgsrc')
      }
    },
    fileSuccess(response, file, fileList) {
      this.formData.advimgsrc = response.data.savePath
      // this.$refs.formRef.validateField('advimgsrc')
      // console.log(1111111111)
    },
    fileBeforeRemove(file, fileList) {
      // console.log(fileList.length)

    },
    // 删除
    handlerDel(id) {
      this.$confirm('确认删除？')
        .then(async(_) => {
          await delImgApi(id)
          this.$message.success('删除成功！')
          if (this.pageData.page > 1 && this.tableData.length === 1) {
            this.pageData.page--
          }
          this.getImgList()
        })
        .catch((_) => {})
    },
    // 编辑回显
    async handlerEdit(type, id) {
      this.fileList = []
      console.log(type, id)
      this.formType = type
      this.title = '修改广告图'
      this.visible = true
      const res = await getImgInfoApi(id)
      console.log(res)
      // 回显的数组
      this.fileList.push({ url: this.$ImgUrl + res.advimgsrc })
      this.formData = {
        ...res
      }
      if (this.fileList.length > 0) this.btnisShow = false
    }
  }
}
</script>

<style lang="less" scoped>
.container {
  padding: 20px;
  background-color: #fff;
}
.el-container {
  background-color: #fff;
  padding: 20px;
}
.el-input {
  width: 230px;
}

.label {
  font-size: 14px;
  color: #606266;
  font-weight: 700;
}
.box {
  display: flex;
  justify-content: space-between;
}
.el-pagination {
  text-align: right;

  margin-top: 20px;
}
.title {
  font-size: 14px;
  font-weight: 700;
}

/deep/.el-dialog__header {
  background: #fafafa;
}

.mr {
  margin-right: 10px;
}
</style>
